package com.zhoug.demo.viewpermission.network;


import com.zhoug.common.http.interceptors.HttpLogInterceptor;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava2.RxJava2CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;
import retrofit2.converter.scalars.ScalarsConverterFactory;

/**
 * @author: zhoug
 * @since: 2025-06-12
 */
public class HttpClient {
    private static final String BASE_URL = "http://192.168.0.31:48889/";
    private Retrofit mRetrofit;
    private ViewPermissionApi mViewPermissionApi;

    private static final class HttpClientHolder {
        private static final HttpClient httpClient = new HttpClient();
    }

    public static HttpClient get() {
        return HttpClientHolder.httpClient;
    }

    public HttpClient() {
        HttpLogInterceptor httpLogInterceptor = new HttpLogInterceptor();
        httpLogInterceptor.setLevel(HttpLogInterceptor.Level.BODY);
        OkHttpClient okHttpClient = new OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS)
                .writeTimeout(30, TimeUnit.SECONDS)
                .connectTimeout(10, TimeUnit.SECONDS)
                .retryOnConnectionFailure(true)
                .followRedirects(true)
                .addInterceptor(new TokenInterceptor())
                .addInterceptor(httpLogInterceptor)
                .build();

        mRetrofit = new Retrofit.Builder()
                .client(okHttpClient)
                .baseUrl(BASE_URL)
                .addCallAdapterFactory(RxJava2CallAdapterFactory.create())
                .addConverterFactory(ScalarsConverterFactory.create())
                .addConverterFactory(GsonConverterFactory.create())
                .build();
    }

    public ViewPermissionApi getViewPermissionApi() {
        if (mViewPermissionApi == null) {
            synchronized (this) {
                if (mViewPermissionApi == null) {
                    mViewPermissionApi = mRetrofit.create(ViewPermissionApi.class);
                }
            }
        }
        return mViewPermissionApi;
    }

}
